﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using WFNetLib.WeiXin;
using System.Threading;

namespace 无线打分网站.wx
{
    /// <summary>
    /// wx 的摘要说明
    /// </summary>
    public class wx : IHttpHandler
    {
        public static string TextLogPath = AppDomain.CurrentDomain.BaseDirectory;
        public void ProcessRequest(HttpContext context)
        {

            context.Response.ContentType = "text/plain";
            try
            {
                if (context.Request.HttpMethod.ToLower().Equals("get"))
                { 
                    ValidateUrl();
                    textlog("微信接入校验");
                }
                else if (context.Request.HttpMethod.ToLower().Equals("post"))
                {
                    using (Stream stream = HttpContext.Current.Request.InputStream)
                    {
                        Byte[] postBytes = new Byte[stream.Length];
                        stream.Read(postBytes, 0, (Int32)stream.Length);                        
                        string postString = Encoding.UTF8.GetString(postBytes);
                        MessageProc mp = new MessageProc();
                        mp.encoding = context.Request.ContentEncoding;
                        wxMessage wxMsg = mp.GetMessage(postString);
                        string response="";
                        textlog(wxMsg.MsgType);
                        textlog(wxMsg.Event);
                        textlog(wxMsg.EventKey);
                        switch (wxMsg.MsgType)
                        {
                            case "event":
                                if (wxMsg.Event == "click")
                                {
                                    if (wxMsg.EventKey == "V1001_WJWD")
                                    {
                                        wxMsg.Content = "用户"+wxMsg.FromUserName+"查询温度";
                                        wxMsg.MsgType = "text";                                        
                                    }
                                    else if (wxMsg.EventKey == "V1001_CWXT")
                                    {
                                        wxMsg.MsgType = "news";
                                        wxMsg.ArticleCount = 5;
                                        wxMsg.NewsItemList = new wxMessageNewsItem[5];
                                        wxMsg.NewsItemList[0] = new wxMessageNewsItem();
                                        wxMsg.NewsItemList[0].Title = "物联温度计";
                                        wxMsg.NewsItemList[0].Description = "物联温度计";
                                        wxMsg.NewsItemList[0].PicUrl = "http://wxpj.hrbeu.edu.cn/wx/image/11.jpg";
                                        wxMsg.NewsItemList[0].Url = "http://mp.weixin.qq.com/s?__biz=MzA3Nzg0Njk2OQ==&mid=209076382&idx=1&sn=d089797b1009775bc6142f7ef6cd7f51#rd";

                                        wxMsg.NewsItemList[1] = new wxMessageNewsItem();
                                        wxMsg.NewsItemList[1].Title = "YRH-I型功能特点";
                                        wxMsg.NewsItemList[1].Description = "";
                                        wxMsg.NewsItemList[1].PicUrl = "http://wxpj.hrbeu.edu.cn/wx/image/1.jpg";
                                        wxMsg.NewsItemList[1].Url = "http://mp.weixin.qq.com/s?__biz=MzA3Nzg0Njk2OQ==&mid=209076382&idx=2&sn=3dc174a3120c62b0321271657c29376b#rd";

                                        wxMsg.NewsItemList[2] = new wxMessageNewsItem();
                                        wxMsg.NewsItemList[2].Title = "YRH-III型功能特点";
                                        wxMsg.NewsItemList[2].Description = "";
                                        wxMsg.NewsItemList[2].PicUrl = "http://wxpj.hrbeu.edu.cn/wx/image/10.jpg";
                                        wxMsg.NewsItemList[2].Url = "http://mp.weixin.qq.com/s?__biz=MzA3Nzg0Njk2OQ==&mid=209076382&idx=3&sn=94e3a3d59481bfa8fcd1ddcc7a127543#rd";

                                        wxMsg.NewsItemList[3] = new wxMessageNewsItem();
                                        wxMsg.NewsItemList[3].Title = "YRH-IV型功能特点";
                                        wxMsg.NewsItemList[3].Description = "";
                                        wxMsg.NewsItemList[3].PicUrl = "http://wxpj.hrbeu.edu.cn/wx/image/9.jpg";
                                        wxMsg.NewsItemList[3].Url = "http://mp.weixin.qq.com/s?__biz=MzA3Nzg0Njk2OQ==&mid=209076382&idx=4&sn=05137c15a940c00878c054142bb311e3#rd";

                                        wxMsg.NewsItemList[4] = new wxMessageNewsItem();
                                        wxMsg.NewsItemList[4].Title = "物联温度计安装";
                                        wxMsg.NewsItemList[4].Description = "";
                                        wxMsg.NewsItemList[4].PicUrl = "http://wxpj.hrbeu.edu.cn/wx/image/4.jpg";
                                        wxMsg.NewsItemList[4].Url = "http://mp.weixin.qq.com/s?__biz=MzA3Nzg0Njk2OQ==&mid=209076382&idx=5&sn=d3877b904639b20efa073a57d356ab44#rd";
                                    }
                                    else if (wxMsg.EventKey == "V1001_JCYPT")
                                    {
                                        wxMsg.MsgType = "news";
                                        wxMsg.ArticleCount = 2;
                                        wxMsg.NewsItemList = new wxMessageNewsItem[2];
                                        wxMsg.NewsItemList[0] = new wxMessageNewsItem();
                                        wxMsg.NewsItemList[0].Title = "室温监测云平台";
                                        wxMsg.NewsItemList[0].Description = "室温监测云平台";
                                        wxMsg.NewsItemList[0].PicUrl = "http://wxpj.hrbeu.edu.cn/wx/image/6.jpg";
                                        wxMsg.NewsItemList[0].Url = "http://mp.weixin.qq.com/s?__biz=MzA3Nzg0Njk2OQ==&mid=209081258&idx=1&sn=a64ed628c83146319f93fa4e7d4ca24f&scene=18#rd";

                                        wxMsg.NewsItemList[1] = new wxMessageNewsItem();
                                        wxMsg.NewsItemList[1].Title = "室温监测应用平台简介";
                                        wxMsg.NewsItemList[1].Description = "";
                                        wxMsg.NewsItemList[1].PicUrl = "http://wxpj.hrbeu.edu.cn/wx/image/5.jpg";
                                        wxMsg.NewsItemList[1].Url = "http://mp.weixin.qq.com/s?__biz=MzA3Nzg0Njk2OQ==&mid=209081258&idx=2&sn=9c719276a96e06617c1a6ea877c18337&scene=18#rd";

                                        
                                    }
                                    else if (wxMsg.EventKey == "V1001_RYHJN")
                                    {
                                        wxMsg.MsgType = "news";
                                        wxMsg.ArticleCount = 4;
                                        wxMsg.NewsItemList = new wxMessageNewsItem[4];
                                        wxMsg.NewsItemList[0] = new wxMessageNewsItem();
                                        wxMsg.NewsItemList[0].Title = "热用户节能";
                                        wxMsg.NewsItemList[0].Description = "为响应国家关于推动城市供热数字化系统建设的需求，我公司经过多年的市场及测温技术的摸索，研发出一款克服原有设备";
                                        wxMsg.NewsItemList[0].PicUrl = "http://wxpj.hrbeu.edu.cn/wx/image/8.jpg";
                                        wxMsg.NewsItemList[0].Url = "http://mp.weixin.qq.com/s?__biz=MzA3Nzg0Njk2OQ==&mid=208528127&idx=1&sn=eedea7b455e13d8bf209746ce3c26438&scene=18#rd";

                                        wxMsg.NewsItemList[1] = new wxMessageNewsItem();
                                        wxMsg.NewsItemList[1].Title = "室温监测云平台：末梢节能的一把金钥匙";
                                        wxMsg.NewsItemList[1].Description = "";
                                        wxMsg.NewsItemList[1].PicUrl = "http://wxpj.hrbeu.edu.cn/wx/image/12.jpg";
                                        wxMsg.NewsItemList[1].Url = "http://mp.weixin.qq.com/s?__biz=MzA3Nzg0Njk2OQ==&mid=208528127&idx=2&sn=65224eac039d38948e70e9df7015bd97&scene=18#rd";

                                        wxMsg.NewsItemList[2] = new wxMessageNewsItem();
                                        wxMsg.NewsItemList[2].Title = "室温与供热相关问题";
                                        wxMsg.NewsItemList[2].Description = "室温监测云平台";
                                        wxMsg.NewsItemList[2].PicUrl = "http://wxpj.hrbeu.edu.cn/wx/image/2.jpg";
                                        wxMsg.NewsItemList[2].Url = "http://mp.weixin.qq.com/s?__biz=MzA3Nzg0Njk2OQ==&mid=208528127&idx=3&sn=4dbc41701a484da0a80f30e7fd133145&scene=18#rd";

                                        wxMsg.NewsItemList[3] = new wxMessageNewsItem();
                                        wxMsg.NewsItemList[3].Title = "用科技的“眼睛”观测供热";
                                        wxMsg.NewsItemList[3].Description = "";
                                        wxMsg.NewsItemList[3].PicUrl = "http://wxpj.hrbeu.edu.cn/wx/image/3.jpg";
                                        wxMsg.NewsItemList[3].Url = "http://mp.weixin.qq.com/s?__biz=MzA3Nzg0Njk2OQ==&mid=208528127&idx=4&sn=139e1343fba11e6466c2e3aefa9b1e29&scene=18#rd";
                                    }
                                    else if (wxMsg.EventKey == "V1001_LXWM")
                                    {
                                        wxMsg.MsgType = "news";
                                        wxMsg.ArticleCount = 1;
                                        wxMsg.NewsItemList = new wxMessageNewsItem[1];
                                        wxMsg.NewsItemList[0]=new wxMessageNewsItem();
                                        wxMsg.NewsItemList[0].Title = "联系我们";
                                        wxMsg.NewsItemList[0].Description = "永立盛联-专业供热室温监测平台";
                                        wxMsg.NewsItemList[0].PicUrl = "http://wxpj.hrbeu.edu.cn/wx/image/7.jpg";
                                        wxMsg.NewsItemList[0].Url = "http://mp.weixin.qq.com/s?__biz=MzA3Nzg0Njk2OQ==&mid=208528528&idx=1&sn=5b80192e6f203359e4189daf816a8dea#rd";
                                    }
                                    else
                                    {
                                        wxMsg.Content = "正在开发中.......";
                                        wxMsg.MsgType = "text";
                                    }
                                }
                                else if (wxMsg.EventKey == "view")
                                {
                                    wxMsg.Content = "view事件";
                                    wxMsg.MsgType = "text";
                                }
                                else
                                {
                                    wxMsg.Content = "未知事件";
                                    wxMsg.MsgType = "text";
                                }
                                break;
                            case "text":
                                string str = wxMsg.ToUserName;
                                str += "\r\n";
                                str += wxMsg.FromUserName;
                                str += "\r\n";
                                str += wxMsg.CreateTime;
                                str += "\r\n";
                                str += wxMsg.MsgType;
                                str += "\r\n";
                                str += wxMsg.Content;
                                str += "\r\n";
                                str += wxMsg.MsgId;
                                wxMsg.Content = str;
                                break;
                            default:
                                wxMsg.Content = "未处理消息类型";
                                wxMsg.MsgType = "text";
                                break;
                        }
                        response = mp.MakeTxMsg(wxMsg);
                        context.Response.ContentEncoding= Encoding.UTF8;
                        context.Response.Write(response);
                    }
                }
                else
                {
                    context.Response.Write("wgx:post");
                    textlog("post");
                }
            }
            catch (System.Exception ex)
            {
                context.Response.Write(ex.Message);
                textlog(ex.Message);
            }
            
        }
        public void textlog(string log)
        {
            try
            {
                DateTime dt = DateTime.Now;
                log = log + "\r\n";
                WFNetLib.Log.TextLog.AddTextLog(log + "\r\n", TextLogPath + "\\TextLog\\" + String.Format("{0:D4}", dt.Year) + "-" + String.Format("{0:D2}", dt.Month) + "-" + String.Format("{0:D2}", dt.Day) + "运行信息.txt", false);
            }
            catch
            {

            }
        }
        public void ValidateUrl()
        {
            /* signature    微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
                timestamp    时间戳
                nonce    随机数
                echostr    随机字符串
            */
            //接收请求过来的参数
            HttpContext context = HttpContext.Current;
            string signature = context.Request["signature"];
            string timestamp = context.Request["timestamp"];
            string nonce = context.Request["nonce"];

            string echostr = context.Request["echostr"];

            string token = "weixinduang";
            string[] temp1 = { token, timestamp, nonce };
            //1.字典序排序
            Array.Sort(temp1);
            //2.将3个参数字符串拼接成一个字符串后进行sha1加密
            string str = string.Join("", temp1);
            string strResult = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "SHA1");
            //3.开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
            if (strResult.ToLower().Equals(signature))
            {
                context.Response.Write(echostr);
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}